#encoding=utf-8
import os
import tensorflow as tf
from PIL import Image,ImageFilter
import numpy as np
import matplotlib.pyplot as plt
import re


imgPath = './data/img/'
filename = './data/train.tfrecords'
CLASS = 2

#文件名格式   UUID-类别.png
def getLabel(name):
    m = re.match( r'(.*?)-(.*?).png', name, re.M|re.I)
    if m:
       label = int(m.group(2))
       return label
    else:
       print("No match!!")       
       


#制作二进制数据
def create_record():
    writer = tf.python_io.TFRecordWriter(filename)
    for i in os.listdir(imgPath):        
        img = Image.open(imgPath+i).crop((100, 1600, 300, 1800))
        img = img.resize((28, 28))
        img = img.convert('L')
        img_raw = img.tobytes() #将图片转化为原生bytes
        label = getLabel(i)
        example = tf.train.Example(
           features=tf.train.Features(feature={
                "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
                'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
           }))
        writer.write(example.SerializeToString())
    writer.close()

data = create_record()


#读取二进制数据
def read_and_decode():
    # 创建文件队列,不限读取的数量
    filename_queue = tf.train.string_input_producer([filename])
    # create a reader from file queue
    reader = tf.TFRecordReader()
    # reader从文件队列中读入一个序列化的样本
    _, serialized_example = reader.read(filename_queue)
    # get feature from serialized example
    # 解析符号化的样本
    features = tf.parse_single_example(
        serialized_example,
        features={
            'label': tf.FixedLenFeature([], tf.int64),
            'img_raw': tf.FixedLenFeature([], tf.string)
        }
    )
    label = features['label']
    label = tf.cast(label, tf.int32)
    label = tf.one_hot(label,CLASS,1,0) 
    img = features['img_raw']    
    img = tf.decode_raw(img, tf.uint8)
    img = tf.reshape(img, [28,28, 1])
    img = tf.cast(img, tf.float32) * (1. / 255) - 0.5
    
    return img, label
    


img, label = read_and_decode()
print("tengxing",img,label)
#使用shuffle_batch可以随机打乱输入 next_batch挨着往下取
# shuffle_batch才能实现[img,label]的同步,也即特征和label的同步,不然可能输入的特征和label不匹配
# 比如只有这样使用,才能使img和label一一对应,每次提取一个image和对应的label
# shuffle_batch返回的值就是RandomShuffleQueue.dequeue_many()的结果
# Shuffle_batch构建了一个RandomShuffleQueue，并不断地把单个的[img,label],送入队列中
img_batch, label_batch = tf.train.shuffle_batch([img, label],
                                            batch_size=2, capacity=2000,
                                            min_after_dequeue=1000)

# 初始化所有的op
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    fig = plt.figure()
    for i in range(1):
        val, l = sess.run([img_batch, label_batch])
        print(val.shape, l)
        plt.subplot(1,1,i+1)
        plt.imshow(val[0].reshape(28,28),cmap='gray')
        
    plt.show()
    coord.request_stop()
    coord.join(threads)
    